<!-- 财务设置->币种设置 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="business-big-box" style="margin:2px 8px;">
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :span="2" v-if="permissions.includes('currency:add')">
                            <div class="btns" @click="add">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="permissions.includes('currency:edit')">
                            <div class="btns" @click="edit">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="permissions.includes('currency:delete')">
                            <div class="btns" @click="remove">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div class="resize-table-container" style="width:800px">
                <a-table :columns="columns" :data-source="data" bordered :scroll="{ x: 0, y: 500}" :pagination="pagination" style="font-size: 12px;"
                    :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}" @change="onTableChange">
                </a-table>
            </div>

            <a-modal v-model="editModal" :title="editItem.id ? '编辑币种' : '新增币种'" width="600px" :dialog-style="{ top: '20px' }">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" layout='Horizontal' :form="form" :label-col="{ span: 10 }" :wrapper-col="{ span: 16}" style="padding:0;padding-right:24px;">
                        <a-row :gutter=[0,0]>
                            <a-col :span="12">
                                <a-form-item label="币种编码">
                                    <a-input maxLength="2" onkeyup="value=value.toString().match(/^\d+(?:\.\d{0,5})?/)" autocomplete="off"
                                        v-decorator="['code', { rules: [{ required: true, message: '币种编码不能为空' }] }]" placeholder="长度两位，如：01" :disabled="isDisabled" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="币种名称">
                                    <a-input autocomplete="off" v-decorator="['name', { rules: [{ required: true, message: '币种名称不能为空' }] }]" placeholder="请输入币种名称" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="币符">
                                    <a-input autocomplete="off" v-decorator="['currencySign', { rules: [{ required: false, message: '币符不能为空' }] }]" placeholder="请输入币符" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="本位币">
                                    <a-checkbox v-model="isBaseCurrency" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24" style="margin-left:-109px;" v-show="!isBaseCurrency">
                                <a-form-item label="汇率类型">
                                    <a-radio-group v-model="exChangeRateType" @change="handleRateType">
                                        <a-radio :value="1">固定汇率</a-radio>
                                        <a-radio :value="2">浮动汇率</a-radio>
                                    </a-radio-group>
                                </a-form-item>
                            </a-col>
                            <a-col :span="24" style="margin-left:-109px;" v-show="!isBaseCurrency">
                                <a-form-item label="折算方式">
                                    <a-radio-group v-model="calDirection">
                                        <a-radio :value="1">原币*汇率=本位币</a-radio>
                                        <a-radio :value="2">原币/汇率=本位币</a-radio>
                                    </a-radio-group>

                                    <!-- <a-select v-decorator="['calDirection', { rules: [{ required: true, message: '请选择折算方式' }] }]" placeholder="折算方式">
                                        <a-select-option value="1">原币*汇率=本位币</a-select-option>
                                        <a-select-option value="2">原币/汇率=本位币</a-select-option>
                                    </a-select> -->
                                </a-form-item>
                            </a-col>
                            <!-- <a-col :span="12">
                                <a-form-item label="最大折算误差">
                                    <a-input placeholder="请输入最大折算误差" value="0.00" read-only />
                                </a-form-item>
                            </a-col> -->
                            <!-- <a-col :span="12">
                                <a-form-item label="汇率设类型">
                                    <a-select v-decorator="['exChangeRateType', { rules: [{ required: true, message: '请选择汇率' }] }]" placeholder="汇率设置方式">
                                        <a-select-option value="1">日汇率</a-select-option>
                                        <a-select-option value="2">月汇率</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col> -->
                            <a-col :span="12" v-if="exChangeRateType == 1" v-show="!isBaseCurrency" class="ex-class">
                                <a-form-item label="期间">
                                    <a-input read-only :value="moment().format('YYYY')" style="width: 100px;"></a-input>
                                    <!-- <a-input-number style="width: 200px;" size="large" v-decorator="['accountYear', { rules: [{ required: true, message: '年份不能为空' }] }]" placeholder="请输入年份" :min="2020" @change="onChange" /> -->
                                </a-form-item>
                            </a-col>
                            <a-col :span="12" v-if="exChangeRateType == 2" v-show="!isBaseCurrency" class="ex-class">
                                <a-form-item label="期间">
                                    <a-month-picker :disabled-date="disabledDate" :defaultValue="moment().format('YYYY-MM')" v-model="choiceMonth" @change="onChangeMonth" style="width: 100px;" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                    <div style="min-height:300px;" class="currency-table" v-show="!isBaseCurrency">
                        <a-table v-if="exChangeRateType == 1" :columns="accountColumnsMonth" :data-source="accountData" bordered style="font-size: 12px;" :scroll="{x:0,y:240}" :pagination="false">
                            <template slot="exchangeRate" slot-scope="text,record,index">
                                <a-input :value="text" onkeyup="value=value.toString().match(/^\d+(?:\.\d{0,5})?/)" @blur="e => onCellText(1,index, 'exchangeRate', e.target.value)"></a-input>
                            </template>
                            <template slot="adjustExchangeRate" slot-scope="text,record,index">
                                <a-input :value="text" onkeyup="value=value.toString().match(/^\d+(?:\.\d{0,5})?/)" @blur="e => onCellText(1,index, 'adjustExchangeRate', e.target.value)"></a-input>
                            </template>
                        </a-table>
                        <a-table v-if="exChangeRateType == 2" :columns="accountColumnsDay" :data-source="accountDataDay" bordered style="font-size: 12px;" :scroll="{x:0,y:240}" :pagination="false">
                            <template slot="exchangeRate" slot-scope="text,record,index">
                                <a-input :value="text" onkeyup="value=value.toString().match(/^\d+(?:\.\d{0,5})?/)" @blur="e => onCellText(2,index, 'exchangeRate', e.target.value)"></a-input>
                            </template>
                            <template slot="adjustExchangeRate" slot-scope="text,record,index">
                                <a-input :value="text" onkeyup="value=value.toString().match(/^\d+(?:\.\d{0,5})?/)" @blur="e => onCellText(2,index, 'adjustExchangeRate', e.target.value)"></a-input>
                            </template>
                        </a-table>
                    </div>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="handleSubmit" v-if="permissions.includes('currency:save')">保存</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                </template>
            </a-modal>
        </div>
    </div>
</template>
<script>
import { mapState } from "vuex";
import table from "@/mixins/table";
import moment from "moment";
import { pageList, save, deleteCurrency, getDetail } from "@/api/erp/currency";

export default {
    mixins: [table],
    watch: {
        isBaseCurrency (val) {
            if (val) {
                this.exChangeRateType = 1;
                this.calDirection = 1;
                this.monthDataFun();
            }
        }
    },
    data () {
        const columns = [
            {
                align: "left",
                title: "币名",
                dataIndex: "name",
                width: "120"
            },
            {
                align: "left",
                title: "币种编码",
                dataIndex: "code",
                width: "120"
            },
            {
                align: "left",
                title: "币符号",
                dataIndex: "currencySign",
                width: "120"
            },
            {
                align: "left",
                title: "是否是本位币",
                dataIndex: "isBaseCurrency",
                width: "120",
                customRender: (text, row, index) => {
                    return text ? "是" : "否";
                }
            },
            {
                align: "left",
                title: "汇率类型",
                dataIndex: "exChangeRateType",
                width: "120",
                customRender: (text, row, index) => {
                    return text == 1 ? "固定汇率" : text == 2 ? "浮动汇率" : "";
                }
            },
            {
                align: "left",
                title: "折算方式",
                dataIndex: "calDirection",
                width: "120",
                customRender: (text, row, index) => {
                    return text == 1 ? "原币*汇率=本位币" : text == 2 ? "原币/汇率=本位币" : "";
                }
            },
        ];

        const accountColumnsDay = [
            {
                align: "center",
                title: "序号",
                dataIndex: "index",
                width: 40,
                customRender: (text, record, index) => {
                    return index + 1
                }
            },
            {
                align: "center",
                title: "日期",
                dataIndex: "dateTitle",
                width: 120
            },
            {
                align: "left",
                title: "记账汇率",
                dataIndex: "exchangeRate",
                scopedSlots: { customRender: "exchangeRate" }
            },
            {
                align: "left",
                title: "调整汇率",
                dataIndex: "adjustExchangeRate",
                scopedSlots: { customRender: "adjustExchangeRate" }
            },
        ];
        const accountColumnsMonth = [
            {
                align: "center",
                title: "序号",
                dataIndex: "index",
                width: 40,
                customRender: (text, record, index) => {
                    return index + 1
                }
            },
            {
                align: "center",
                title: "月份",
                dataIndex: "dateTitle",
                width: 120
            },
            {
                align: "left",
                title: "记账汇率",
                dataIndex: "exchangeRate",
                scopedSlots: { customRender: "exchangeRate" }
            },
            {
                align: "left",
                title: "调整汇率",
                dataIndex: "adjustExchangeRate",
                scopedSlots: { customRender: "adjustExchangeRate" }
            },
        ];

        return {
            editItem: {}, //新增/编辑对象
            editModal: false,
            visible: false,
            selectedKeys: [],
            selectedData: {},
            selectedIds: [],
            columns,
            accountColumnsDay,
            accountColumnsMonth,
            accountData: [],
            accountDataDay: [],
            accountDataDayTemp: [],//存储对比值
            exChangeRateType: 1,
            calDirection: 1,
            data: [],
            text: null,
            dayNum: 0,//当前月天数
            form: this.$form.createForm(this, { name: "advanced_search" }),
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
              条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            choiceMonth: moment().format('YYYY-MM'),
            isBaseCurrency: false,
            postData: {
                "current": 1,
                "size": 20
            },
            orderList: [],//保存的数据
            currentId: null,
        };
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    mounted () {
        this.PageList();
    },
    methods: {
        moment,
        disabledDate (current) {
            // Can not select days before today and today
            // console.log(current);
            // return current && current < moment().endOf('month');
        },
        // 获取列表
        PageList () {
            const { postData } = this;
            pageList(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.data = records;
                    Object.assign(this.pagination, {
                        total
                    });
                }
            }).catch(error => { });
        },
        handleSubmit (e) {
            e.preventDefault();
            this.form.validateFields((err, values) => {
                console.log(values);
                let request = {};

                request = { ...values };
                request.id = this.currentId;

                request.isBaseCurrency = this.isBaseCurrency;
                console.log(values);
                if (!this.isBaseCurrency) {//是否本位币

                    request.exChangeRateType = this.exChangeRateType;//汇率类型
                    request.calDirection = this.calDirection;//折算方式
                    if (this.exChangeRateType == 1) {
                        console.log(values);
                        //月汇率
                        request.orderList = this.accountData;
                    } else if (this.exChangeRateType == 2) {
                        console.log(values);
                        //日汇率
                        request.orderList = this.accountDataDay;
                    }
                }
                console.log('提交的数据：', request);
                if (request.code.length != 2) {
                    this.$message.warning('币种编码必须为两位数字');
                    return;
                }
                if (!err) {
                    save(request).then(response => {
                        if (response.code === 200) {
                            this.$message.success("保存成功");
                            //刷新 列表
                            this.editModal = false;
                            this.PageList();
                            this.selectedKeys = [];
                            this.selectedData = [];
                        } 
                    })
                }
            });
        },
        onChangeMonth (k, v) {
            this.choiceMonth = v;


            // let isTrue = _.isMatch(this.accountDataDay, this.accountDataDayTemp);

            // let isHave = this.accountDataDay.filter(item => item.exchangeRate != null || item.adjustExchangeRate != null);

            let _this = this;
            this.$confirm({
                title: '提示',
                content: '数据未保存是否切换月份？',
                onOk () {
                    if (_this.currentId) {
                        _this.getDetailCurr();
                    } else {
                        _this.dayDataFun();
                    }

                },
                onCancel () { },
            });




            // for (let i = 0; i < this.accountDataDay.length; i++) {
            //     if (this.accountDataDay[i].exchangeRate != null || this.accountDataDay[i].adjustExchangeRate != null) {
            //         let _this = this;
            //         this.$confirm({
            //             title: '提示',
            //             content: '数据未保存是否切换月份？',
            //             onOk() {
            //                 _this.getDetailCurr();
            //             },
            //             onCancel() { },
            //         });
            //         return;
            //     } else {
            //         this.dayDataFun();
            //         return;
            //     }
            // }

        },
        handleRateType (e) {
            if (e.target.value == 1) {
                this.monthDataFun();
            }
            if (e.target.value == 2) {
                this.dayDataFun();
            }
            if (this.currentId) {
                this.getDetailCurr();
            }
        },
        hideModal () {
            this.editModal = false;
        },
        add () {
            this.form = this.$form.createForm(this, {});
            this.form.title = "新增外币";
            this.isBaseCurrency = false;
            this.currentId = null;
            this.editModal = true;
            this.monthDataFun();
        },
        dayDataFun () {
            //当前月天数
            this.accountDataDay = []
            let da = this.choiceMonth.split('-');
            var day = new Date(da[0], da[1], 0);
            this.dayNum = day.getDate();
            console.log('this.dayNu:', this.dayNum);
            for (let i = 0; i < this.dayNum; i++) {
                let array = {
                    year: da[0],
                    month: da[1],
                    date: this.choiceMonth + '-' + (i + 1),
                    dateTitle: da[0] + '年' + da[1] + '月' + (i + 1) + '日',
                    exchangeRate: null,
                    adjustExchangeRate: null,
                    type: 2,
                }
                this.accountDataDay.push(array)
            }
        },
        monthDataFun () {
            //当前年月份
            this.accountData = []
            for (let i = 0; i < 12; i++) {
                let array = {
                    year: new Date().getFullYear(),
                    month: i + 1,
                    date: null,
                    dateTitle: new Date().getFullYear() + '年' + (i + 1) + '月',
                    exchangeRate: null,
                    adjustExchangeRate: null,
                    type: 1,
                }
                this.accountData.push(array)
            }
        },
        getYearDayTotal () {
            //获取当前年总共好多天
            this.accountDataDay = [];

            let da = this.choiceMonth.split('-');

            for (let j = 0; j < 12; j++) {
                let day = new Date(da[0], (j + 1), 0);
                let dayNum = day.getDate();

                for (let i = 0; i < dayNum; i++) {
                    let array = {
                        year: da[0],
                        month: (j + 1),
                        date: da[0] + '-' + (j + 1) + '-' + (i + 1),
                        dateTitle: da[0] + '年' + (j + 1) + '月' + (i + 1) + '日',
                        exchangeRate: null,
                        adjustExchangeRate: null,
                        type: 1,
                    }
                    this.accountDataDay.push(array);
                }
            }
            this.dayDataFun();

            console.log('this.accountDataDay:', this.accountDataDay);


        },
        onCellText (type, indexTab, code, value) {
            if (type == 1) {
                //月汇率
                console.log(indexTab, code, value);

                let target = this.accountData.find((item, index) => index === indexTab);
                if (Number(value)) {
                    target[code] = Number(value).toFixed(2);
                } else {
                    target[code] = null;
                }

                console.log('this.accountData:', this.accountData);

            } else if (type == 2) {
                //日汇率
                let target = this.accountDataDay.find((item, index) => index === indexTab);
                if (Number(value)) {
                    target[code] = Number(value).toFixed(2);
                } else {
                    target[code] = null;
                }
                console.log('this.accountDataDay:', this.accountDataDay);
            }

        },
        edit () {
            if (this.selectedKeys.length != 1) {
                this.$message.warning("请选择一条数据");
                return;
            }
            this.editModal = true
            this.editItem = { ... this.selectedData };
            console.log(this.editItem);

            this.currentId = this.selectedData.id;
            this.exChangeRateType = this.selectedData.exChangeRateType;
            this.isBaseCurrency = this.selectedData.isBaseCurrency;
            this.calDirection = this.selectedData.calDirection;

            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        name: this.$form.createFormField({
                            value: this.editItem.name
                        }),
                        code: this.$form.createFormField({
                            value: this.editItem.code
                        }),
                        currencySign: this.$form.createFormField({
                            value: this.editItem.currencySign
                        }),
                        // calDirection: this.$form.createFormField({
                        //     value: this.editItem.calDirection
                        // }),
                        // exChangeRateType: this.$form.createFormField({
                        //     value: this.editItem.exChangeRateType + ""
                        // }),
                        // accountYear: this.$form.createFormField({
                        //     value: this.editItem.accountYear
                        // }),
                    };
                }
            });
            this.getDetailCurr();
        },
        getDetailCurr () {
            //获取币种明细
            let request = {};
            if (this.exChangeRateType == 1) {
                request = {
                    currencyId: this.currentId,
                    year: new Date().getFullYear(),
                    month: null,
                }
            } else {
                request = {
                    currencyId: this.currentId,
                    year: new Date().getFullYear(),
                    month: this.choiceMonth.split('-')[1],
                }
            }
            getDetail(request).then(res => {
                if (res.code === 200) {
                    if (this.exChangeRateType == 1) {
                        if (res.data.length > 0 && res.data.filter(item => item.type == 1).length > 0) {
                            this.accountData = res.data;
                        } else {
                            this.monthDataFun();
                        }
                    } else {
                        if (res.data.length > 0 && res.data.filter(item => item.type == 2).length > 0) {
                            this.accountDataDay = res.data;
                            this.accountDataDayTemp = _.cloneDeep(res.data);
                        } else {
                            this.dayDataFun();
                        }
                    }
                }
            })
        },
        remove () {
          if (this.selectedKeys.length < 1) {
              this.$message.warning("请选择一条数据");
              return;
          }
          let _this = this;
          this.$confirm({
            title: '提示',
            content: '您确定要删除该币种吗？',
            onOk() {
                deleteCurrency(_this.selectedIds).then(res => {
                    if (res.code == 200) {
                        _this.PageList();
                        _this.selectedKeys = [];
                        _this.selectedData = [];
                        _this.$message.success("删除成功");
                    }
                });
            },
            onCancel() {
            },
          });
        },
        changePageSize (e) {
            const value = e.target.value;
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData, {
                "size": value
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value)
            });
        },
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                "current": pagination.current,
                "size": pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageList();
        },
        onCellChange (item, dataIndex, editValue) {
            if (item[dataIndex] != editValue) {
                const edit = { id: item.id, [dataIndex]: editValue };
                this.TreeSortEditList.set(item.id, edit);
            } else {
                this.TreeSortEditList.delete(item.id);
            }
            console.log([...this.TreeSortEditList.values()]);
        },
        selection (keys, row) {
            this.selectedKeys = [];
            this.selectedKeys = keys;
            this.selectedData = row[0];
            const ids = new Array();
            row.forEach(function (val) {
                ids.push(val.id);
            });
            this.selectedIds = ids;
            console.log("rowKeys", this.selectedData);
        },
    }
};
</script>
<style scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
        margin-bottom: 0px !important;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
    /* .crm-btn {
              margin-left: 10px;
              margin-bottom: 10px;
            } */
</style>
<style lang="less">
    @import '~@/style/setting/business.less';
    .currency-table {
        .ant-input {
            border: none;
            text-align: right;
        }
    }
    .ex-class {
        margin-left: -68px;
    }
</style>
